#-*- coding: utf-8 -*-
'''
Created on 2017-12-14

@author: minjie.qu
'''

import smtplib
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.header import Header

# 第三方 SMTP 服务
mail_host="smtp.189.cn"  #设置服务器
mail_post= 25  # 25 为 SMTP 端口号
mail_user="xxxxxx@189.cn"    #用户名
mail_pass="xxxxxx"   #口令

sender = 'xxxxxx@189.cn'
receivers =['xxxxxx@qq.com','xxxxxx@126.com']  # 接收邮件，可设置为你的QQ邮箱或者其他邮箱

def tips_success():
    msgRoot = MIMEMultipart('related')
    msgRoot['From'] = Header("12306", 'utf-8')
    msgRoot['To'] =  Header("xxxxxx@qq.com;xxxxxx@126.com", 'utf-8')
    subject = '购票成功,尽快完成支付!'
    msgRoot['Subject'] = Header(subject, 'utf-8')
    print ("1、邮件基本信息设置成功")
    
    msgAlternative = MIMEMultipart('alternative')
    msgRoot.attach(msgAlternative)
     
    mail_msg = """
    <p>恭喜您,下单成功!请尽快前往12306,完成后续支付操作,以免订单超时,请知晓,谢谢！...</p>
    <p>登录页面：<a href="https://kyfw.12306.cn/otn/login/init">12306</a></p>
    <p><img src="cid:image"></p>
    """
    msgAlternative.attach(MIMEText(mail_msg, 'html', 'utf-8'))
    print ("2、邮件HTML格式设置成功")
    
    # 指定图片为当前目录
    fp = open('login12306.png', 'rb')
    msgImage = MIMEImage(fp.read())
    fp.close()
     
    # 定义图片 ID，在 HTML 文本中引用
    msgImage.add_header('Content-ID', '<image1>')
    msgRoot.attach(msgImage)
    print ("3、邮件正文图片添加成功")
    
    try:
        print ("4、邮件服务连接建立开始")
        smtpObj = smtplib.SMTP() 
        smtpObj.connect(mail_host, mail_post)    # 25 为 SMTP 端口号
        smtpObj.login(mail_user,mail_pass)
        print ("5、邮件服务连接建立成功")
    
        print ("6、邮件发送开始")
        smtpObj.sendmail(sender, receivers, msgRoot.as_string())
        print ("7、邮件发送成功")
        
    except smtplib.SMTPException:
        print ("8、邮件发送失败")
        
    print ("9、邮件发送结束")
    
if __name__ == '__main__':
    tips_success()